import { getCurrentInstance, toRefs, reactive, onMounted } from 'vue'
import { ElLoading, ElMessageBox, ElMessage } from 'element-plus'
export default (pData) => {
  const { proxy } = getCurrentInstance()
  let proxyData = pData || {}

  onMounted(() => {
    if (!pData) {
      const { data } = getCurrentInstance()
      proxyData = data
    }
  })
  
  const ctx = reactive({
    loading: false, // 遮罩层
    total: 0, // 总条数
    tableList: [], // 表格数据
    open: false, // 弹出层标题
    title: '', // 标题
    fetch: {},
    single: true, // 非单个禁用
    multiple: true, // 非多个禁用
    showSearch: true, // 显示搜索条件
    handleLoading: undefined, // 操作loading
    ids: [] // 选中数组
  })

  /** 查询列表 */
  const getList = () => {
    const queryParams = proxyData.queryParams
    for (const key in queryParams) {
      if (queryParams[key] === '') {
        queryParams[key] = undefined
      }
    }
    // ctx.loading = true
    openLoading()
    return proxyData.fetch.get(queryParams).then(response => {
      ctx.tableList = response.data.page_data || []
      // 非第一页没有数据 向前跳转一页
      if (queryParams.page > 1 && ctx.tableList.length === 0) {
        queryParams.page--
        getList()
      }

      ctx.total = response.data?.page_info?.total || 0
      // ctx.loading = false
      closeLoading()
    }).catch(() => {
      // ctx.loading = false
      closeLoading()
    })
  }

  // 取消按钮
  const cancel = (fn) => {
    ctx.open = false
    proxyData.reset()
    isFunction(fn) && fn()
  }

  // 添加
  const handleAdd = (fn) => {
    proxyData.reset()
    ctx.open = true
    ctx.title = '添加' + proxyData.fetch.title
    isFunction(fn) && fn()
  }
  // 修改
  const handleEdit = (row, fn) => {
    proxyData.reset()
    const id = row.id || ctx.ids
    document.querySelector('button:focus')?.blur()
    proxyData.fetch.getItem(id).then(response => {
      proxyData.form.value = response.data
      isFunction(fn) && fn(response.data)
      ctx.open = true
      ctx.title = '修改' + proxyData.fetch.title
    })
  }
  const handleUpdate = handleEdit
  /** 删除按钮操作 */
  const handleDelete = (row) => {
    const queryParams = proxyData.queryParams
    const ids = row.id || ctx.ids
    var title = ''
    document.querySelector('button:focus')?.blur()
    if (ids.length > 1) {
      title = '确认要删除选中的数据吗?'
    } else {
      title = '确认要删除这条数据吗?'
    }
    ElMessageBox.confirm(title, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
    ).then(() => {
      return proxyData.fetch.del(ids)
    }).then(() => {
      // 如果删除最后一页全部数据/最后一条数据，删除成功自动向前减一页 
      if ((queryParams.page > 1 && ctx.tableList.length <= 1) || (queryParams.page > 1 && (ctx.tableList.length == ctx.ids.length))) {
        queryParams.page--
      }
      msgSuccess('删除成功')
      getList()
    }).catch(() => {})
  }
  /** 搜索按钮操作 */
  const handleQuery = () => {
    proxyData.queryParams.page = 1
    getList()
  }
  /** 重置操作 */
  const resetQuery = () => {
    resetForm('queryForm')
    handleQuery()
  }
  // 多选框选中数据
  const handleSelectionChange = (selection) => {
    ctx.ids = selection.map(item => item.id)
    ctx.single = selection.length !== 1
    ctx.multiple = !selection.length
    proxy.$emit('multiple', ctx.multiple)
  }
  /** 提交按钮  */
  const submitForm = (before) => {
    if (!isFunction(before)) {
      before = () => true
    }
    proxy.$refs['formRef'].validate(valid => {
      if (before() && valid) {
        openLoading()
        if (proxyData.form.value.id) {
          proxyData.fetch.update(proxyData.form.value).then(() => {
            msgSuccess('修改成功')
            ctx.open = false
            getList()
            closeLoading()
            proxyData.reset()
          }).catch(() => {
            closeLoading()
          })
        } else {
          // delete proxyData.form.id
          proxyData.fetch.add(proxyData.form.value).then(() => {
            msgSuccess('新增成功')
            ctx.open = false
            getList()
            closeLoading()
          }).catch(() => {
            closeLoading()
          })
        }
      } else {
        msgError('请完善表单')
      }
    })
  }
  const resetForm = (refName) => {
    if (proxy.$refs[refName]) {
      proxy.$refs[refName].resetFields();
    }
  }
  // 开启loading
  const openLoading = (text) => {
    if (ctx.handleLoading) return
    ctx.loading = false
    ctx.handleLoading = ElLoading.service({
      lock: true,
      text: text || 'loading...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.3)'
    })
  }
  // 关闭loading
  const closeLoading = () => {
    ctx.handleLoading?.close()
    ctx.handleLoading = null
  }
  /** 导出操作 */
  const handleExport = () => {
    const queryParams = proxyData.queryParams
    if ('dateRange' in queryParams) {
      queryParams.dateRange = queryParams.dateRange || []
      if (queryParams.dateRange.length > 0) {
        queryParams.beginTime = new Date(queryParams.dateRange[0]).Format('yyyy-MM-dd 00:00:00')
        queryParams.endTime = new Date(queryParams.dateRange[1]).Format('yyyy-MM-dd 23:59:59')
      } else {
        queryParams.beginTime = undefined
        queryParams.endTime = undefined
      } 
    }
    const params = { ...queryParams, page: undefined, rows: undefined }
    ElMessageBox.confirm('确认导出所有数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      return proxyData.fetch.export(params)
    }).then(() => {
      msgSuccess('导出成功')
    })
  }

  const msgSuccess = (msg) => {
    ElMessage({ showClose: true, message: msg, type: 'success' })
  }
  const msgError = (msg) => {
    ElMessage({ showClose: true, message: msg, type: 'error' })
  }
  const msgInfo = (msg) => {
    ElMessage({ showClose: true, message: msg, type: 'info' })
  }

  const isFunction = (fn) => {
    return fn && typeof fn == 'function'
  }

  return {
    ...toRefs(ctx),
    getList,
    cancel,
    handleAdd,
    handleEdit,
    handleUpdate,
    handleDelete,
    handleQuery,
    resetQuery,
    handleSelectionChange,
    submitForm,
    openLoading,
    closeLoading,
    handleExport,
    isFunction,
    resetForm,
    msgSuccess,
    msgError,
    msgInfo
  }
}
